package sctu.edu.java.year2016.team02.project.pc.UI;



import sctu.edu.java.year2016.team02.project.pc.problem.PcProblem;
import sctu.edu.java.year2016.team02.project.pc.problem.SocketListener;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.util.List;

/**
 * Created by Eoly on 2016/6/11.
 */
//登陆管理员的登陆对话框
public class LoginUI extends JDialog implements ActionListener{
    private Button login;
    private JLabel user;
    private JLabel key;
    private JTextField username;
    private JPasswordField keywords;
    public boolean isRight = false;

    public LoginUI(JFrame praent, String title,boolean modal){
        super(praent,title,modal);
        Init();
        add(user);
        add(username);
        add(key);
        add(keywords);
        add(login);
        setLayout(null);
        setBounds(SocketListener.screenWidth / 3, SocketListener.ScreenHeight / 4, 300, 180);
        setResizable(false);
        setVisible(true);
    }

    private void Init(){
        login = new Button("Login");
        user = new JLabel("Username:");
        key = new JLabel("Key-words:");
        username = new JTextField("admin");
        keywords = new JPasswordField("123456");
        user.setBounds(40,20,75,25);
        username.setBounds(125,20,125,25);
        key.setBounds(40,65,75,25);
        keywords.setBounds(125,65,125,25);
        login.setBounds(175,110,75,25);
        login.addActionListener(this);
}

    @Override
    public void actionPerformed(ActionEvent e) {
        if(e.getSource()==login){
            String InName = username.getText();
            String InKeyWords = new String(keywords.getPassword());
            String[] nStr ={""};
            List<Object[]> list=null;
            try {
                list= PcProblem.select("NetAdmin", nStr, nStr, false);
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            for(int i=0;i<list.size();i++) {
                Object[] theResult = list.get(i);
                String user = (String)theResult[0];
                String key = (String)theResult[1];
                isRight = InKeyWords.equals(user)&&InName.equals(key)||isRight;
            }
            if(isRight){
                setVisible(false);
            }else{
                JOptionPane.showMessageDialog(this, "账号或密码错误", "提示", JOptionPane.PLAIN_MESSAGE);
                username.setText("");
                keywords.setText("");
            }
        }
    }
}
